import React, { useState, useEffect, useRef } from 'react'
import { message } from 'antd';
import chinaDivision from './../../../utils/chinaDivision';
import AddOption from './addOption/AddOption';
import myAxios from '../../../utils/myAxios';
import {
  Form,
  Input,
  Button,
  Select,
  DatePicker,
  Space,
  Cascader,
  Modal
} from 'antd';
import { PlusSquareFilled, ExclamationCircleOutlined } from '@ant-design/icons';
import store from '../../../redux/store';
import { AsyncGetOptionAction } from '../../../redux/action/customerAction/option';
// console.log(chinaDivision);  所有的省市区 数据
const { TextArea } = Input;


export default function Add() {

  const myRef = useRef()
  const { Option } = Select;


  //写一个方法，来处理商品分类
  function bC(arr) {
    let tempArr = []
    arr.forEach(element => {
      tempArr.push(element.bigClass)
    });
    return tempArr
  }

  //初始化，获取所有下拉选项
  useEffect(() => {
    // 获取所有下拉的异步action
    store.dispatch(AsyncGetOptionAction())

    let fn = store.subscribe(() => {
      setjobList(store.getState().customerReducer.optionReducer.customerPosition)
      setcustomerType(store.getState().customerReducer.optionReducer.customerType)
      setcustomerSource(store.getState().customerReducer.optionReducer.customerSource)
      setcustomerIndustry(store.getState().customerReducer.optionReducer.customerIndustry)
      setcustomerLevel(store.getState().customerReducer.optionReducer.customerLevel)
      setbigClass(bC(store.getState().customerReducer.optionReducer.comSort))
    })
    return () => {
      fn()
    }
  }, [])


  const [jobList, setjobList] = useState([]);
  const [customerType, setcustomerType] = useState([]);
  const [customerSource, setcustomerSource] = useState([]);
  const [customerIndustry, setcustomerIndustry] = useState([]);
  const [customerLevel, setcustomerLevel] = useState([]);
  const [bigClass, setbigClass] = useState([]);
  const [smallClass, setsmallClass] = useState([]);
  const [isModalVisible, setisModalVisible] = useState(false);
  const [toAddOptionData, settoAddOptionData] = useState([]);
  const [toAddOptionType, settoAddOptionType] = useState([]);
  //恢复客户
  const [recover, setrecover] = useState(false);
  //单独存储客户姓名输入框内容
  const [uName, setuName] = useState('');
  //单独再存储表单全部内容
  const [formObj, seformObj] = useState({});

  //点击新增的函数
  function addOption(type, value) {
    //形参type  是点击新增职位，或者新增客户来源 等 的一种标识
    // jobList：表示 新增职位 ，customerType：表示 新增客户类型 ，customerLevel ：表示新增客户级别 ，  customerSource ：表示新增客户来源
    //根据不同的type做判断，点击保存的时候需要去请求不同的接口
    /*    console.log(type);
       console.log(value); */
    settoAddOptionType(type)
    settoAddOptionData(value)
  }
  //提交表单
  const onFinish = (values) => {
    const { customerUsername } = values
    setuName(customerUsername)
    //对日期控件进行数据处理
    let newValue
    if (values['birthDay']) {
      newValue = {
        ...values,
        birthDay: values['birthDay'].format('YYYY-MM-DD'),
      }
      console.log(newValue);
      //如果选择了地区
      let obj = {}
      if (newValue.region) {
        obj = { ...newValue, province: newValue.region[0], city: newValue.region[1], area: newValue.region[2], employeeInputName: 'zhangsan' }
        delete obj.region
      } else {
        obj = { ...newValue, employeeInputName: 'zhangsan' }
      }
      seformObj(obj)
      //发起请求
      addCustomer(obj)

    } else {
      let obj
      if (values.region) {
        obj = { ...values, province: values.region[0], city: values.region[1], area: values.region[2], employeeInputName: 'zhangsan' }
        delete obj.region
      } else {
        obj = { ...values, employeeInputName: 'zhangsan' }
      }

      seformObj(obj)
      //发起请求
      addCustomer(obj)
    }
  }
  //新增客户请求的方法
  function addCustomer(obj, type = 0) {
    let reqUrl
    if (type == 0) {
      reqUrl = '/customer/addCustomer'
    } else {
      reqUrl = '/customer/coverOldCustomer'
    }
    myAxios({
      method: 'post',
      url: reqUrl,
      headers: {
        'isLoading': false
      },
      //data: { ...newValue, province: newValue.region[0], city: newValue.region[1], area: newValue.region[2],employeeInputName:'zhangsan' }
      data: obj
    })
      .then(res => {
        console.log(res.data);
        if (res.data.code == 200) {
          message.success(res.data.msg);
          // 新增成功，清空表单
          form.resetFields()
        } else if (res.data.code == 509) {
          setrecover(true)
        } else {
          message.error(res.data.msg);
        }

      })
  }
  const onFinishFailed = (errorInfo) => {
    console.log('表单验证失败:', errorInfo);
  }

  const [form] = Form.useForm();

  //省市区选择部分
  function onChange(value) {
    console.log(value);
  }

  const handleOk = () => {
    setisModalVisible(false);
  };

  const handleCancel = () => {
    setisModalVisible(false);
  };
  const options = chinaDivision


  const [cities, setCities] = React.useState([]); //smallClass[bigClass[0]]

  //选择了大类以后，再去请求对应小类的数据
  const handleProvinceChange = value => {
    //修改了大类之后，需要把之前选择的小类选项置空
    form.setFieldsValue({
      smallClass: ''
    })
    myAxios({
      method: 'get',
      url: '/customer/customerComSort/findSmallClass',
      headers: {
        'isLoading': false
      },
      params: { bigClass: value }
    })
      .then(res => {
        console.log(res.data.data);
        let tempArr = []
        res.data.data.forEach(item => {
          tempArr.push(item.smallClass)
        })
        setsmallClass(tempArr);
        // setCities(smallClass[value]);
      })

  };
  //选择了小类以后
  const onSecondCityChange = value => {
  };

  //确认恢复客户
  const handleOkrecover = () => {
    setrecover(false);
    myAxios({
      method: 'post',
      url: '/customer/updateRecoveryCustomer',
      params: { customerUsername: uName }
    })
      .then(res => {
        // console.log(res.data);
        if (res.data.code == 200) {
          message.success(res.data.msg)
          // 恢复成功，清空表单
          form.resetFields()
        } else {
          message.error(res.data.msg)
        }
      })
  };
  //取消恢复客户--即覆盖
  const handleCancelrecover = () => {
    setrecover(false);
    //发起请求
    addCustomer(formObj, 1)
  };

  return (
    <>
      <Form
        labelCol={{
          span: 2,
        }}
        wrapperCol={{
          span: 7,
        }}
        layout="horizontal"
        size='small'
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        form={form}
      >
        <Form.Item
          rules={[
            {
              required: true,
              message: '请输入客户名称',
            },
          ]}
          label="客户名称" name="customerUsername">
          <Input />
        </Form.Item>
        <Form.Item label="联系人" name='customerName'>
          <Input />
        </Form.Item>

        <Form.Item label="职位" >
          <Space >
            <Form.Item name='customerPosition'>
              <Select
                placeholder="请选择"
              >
                {
                  jobList.map((item) =>
                    <Select.Option key={item.id} value={item.title}>{item.title}</Select.Option>
                  )
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Button onClick={() => {
                setisModalVisible(true)
                addOption('jobList', jobList)
              }


              } icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}>
                新增
              </Button>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="手机号码" name='phoneNumber'
          rules={[
            {
              pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号'
            },
            {
              required: true,
              message: '请输入手机号码',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="生日" name='birthDay'>
          <DatePicker />
        </Form.Item>
        <Form.Item label="QQ" name="qqNumber">
          <Input />
        </Form.Item>
        <Form.Item label="电子邮箱" name="email"
        >
          <Input />
        </Form.Item>
        <Form.Item label="所在地区" name="region" >
          <Cascader options={options} onChange={onChange} placeholder="请选择" />
        </Form.Item>

        <Form.Item label="详细地址" name="address"  >
          <Input />
        </Form.Item>
        <Form.Item label="邮编" name="postal">
          <Input />
        </Form.Item>
        <Form.Item label="网址" name="website">
          <Input />
        </Form.Item>

        <Form.Item label="客户类型" >
          <Space>
            <Form.Item name='customerType'>
              <Select placeholder="请选择" style={{ width: '170px' }}>
                {
                  customerType.map((item) =>
                    <Select.Option key={item.id} value={item.title}>{item.title}</Select.Option>
                  )
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                onClick={() => {
                  setisModalVisible(true)
                  addOption('customerType', customerType)
                }}
              >新增</Button>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="客户级别">
          <Space>
            <Form.Item name='customerLevel'>
              <Select placeholder="请选择" style={{ width: '170px' }}>
                {
                  customerLevel.map((item) =>
                    <Select.Option key={item.id} value={item.title}>
                      {/* <Rate count={item} disabled value={item} /> */}
                      <span>
                        {item.title}
                      </span>
                    </Select.Option>
                  )
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                onClick={() => {
                  setisModalVisible(true)
                  addOption('customerLevel', customerLevel)
                }}
              >新增</Button>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="客户来源" >
          <Space>
            <Form.Item name='customerSource'>
              <Select placeholder="请选择" style={{ width: '170px' }}>
                {
                  customerSource.map((item) =>
                    <Select.Option key={item.id} value={item.title}>{item.title}</Select.Option>
                  )
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                onClick={() => {
                  setisModalVisible(true)
                  addOption('customerSource', customerSource)
                }}
              >新增</Button>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="所属行业" name='customerIndustry'

        >
          <Select placeholder="请选择">
            {
              customerIndustry.map((item) =>
                <Select.Option key={item.id} value={item.title}>{item.title}</Select.Option>
              )
            }
          </Select>

        </Form.Item>
        <Form.Item label="商品类别" >
          <Space>
            <Form.Item name='bigClass'>
              <Select placeholder='请选择' style={{ width: 120 }} onChange={handleProvinceChange}>
                {bigClass.map(province => (
                  <Option key={province}>{province}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name='smallClass'>
              <Select style={{ width: 120 }} placeholder='请选择' onChange={onSecondCityChange}>
                {smallClass.map(city => (
                  <Option key={city}>{city}</Option>
                ))}
              </Select>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="备注" name="remarks" wrapperCol={{
          span: 9,
        }}>
          <TextArea rows={4} />
        </Form.Item>
        <div style={{ width: '33%', textAlign: 'center' }}>
          <Space>
            <Button style={{ width: 100 }} size='midle' type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={() => { form.resetFields(); }} style={{ width: 100 }} size='midle' danger type="primary" >
              取消
            </Button>
          </Space>
        </div>



      </Form>
      {/* 点击新增职位，新增客户；类型等的模态 */}
      <Modal
        bodyStyle={{ height: 500, overflowY: 'scroll' }}
        title='自定义选项值' visible={isModalVisible} onOk={handleOk}
        onCancel={handleCancel}
        footer={[]}
      >
        <AddOption setisModalAdd={setisModalVisible} toAddOptionType={toAddOptionType} toAddOptionData={toAddOptionData} />
      </Modal>

      {/* 后端设计了一个功能，新增客户的时候，如果客户名称和之前某个被删除的客户名称相同的话，会提示操作者：'该客户信息已被客户管理删除至回收站，是否需要恢复至客户管理！' ，点击是则恢复该客户到客户列表，否则覆盖之前被删除的客户新增为一个全新的客户 */}
      <Modal
        icon={<ExclamationCircleOutlined />}
        title='请选择是否需要恢复客户' visible={recover}
        onOk={handleOkrecover}
        onCancel={handleCancelrecover}
        okText="确认"
        cancelText="取消"
        maskClosable={false}
      >
        <p>该客户信息已被客户管理删除至回收站，是否需要恢复至客户管理！</p>
        <p>确认：恢复客户数据</p>
        <p>取消：覆盖之前的客户数据，新增一个全新的</p>
      </Modal>
    </>
  )
}
